package cn.swu.ws.book;

import cn.swu.ws.dao.MysqlDbDao;
import cn.swu.ws.user.UserServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@WebServlet("/DeleteBook")
public class DeleteBook extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection;
        try {
            connection = MysqlDbDao.login_database();
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        Statement statement;
        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String tem = "delete from %s_book where id = \"%s\"";
        String sql = String.format(tem, UserServlet.user_name,req.getParameter("id"));
        System.out.println(sql);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        String template = "{\n" +
                "\t\"state\": 200,\n" +
                "\t\"delete\": %d,\n" +
                "\t\"login_state\": \" false\",\n" +
                "\t\"data\": null\n" +
                "}";
        Writer writer = resp.getWriter();
        int resultSet = 0;
        try {
            resultSet = statement.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("成功");
        String delete_success = String.format(template, resultSet);
        writer.write(delete_success);
    }
}
